package com.beiding.workordersystem.common.utils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateCalculator {

    public static Date add(Date from, int field, int amount) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(from);
        gc.add(field, amount);
        return gc.getTime();
    }

    public static Date addYear(Date from, int amount) {
        return add(from, Calendar.YEAR, amount);
    }

    public static Date addMoon(Date from, int amount) {
        return add(from, Calendar.MONTH, amount);
    }
    public static Date addDay(Date from, int amount) {
        return add(from, Calendar.DAY_OF_YEAR, amount);
    }

    public static Integer getDayOfMoon(Date data) {
        Calendar c = Calendar.getInstance();
        c.setTime(data);
        return c.get(Calendar.DAY_OF_MONTH);
    }

    public static Integer getDayOfMoonCurrent() {
        return getDayOfMoon(new Date());
    }

    public static Integer getMoonOfYear(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.MONTH) + 1;
    }

    public static Integer getYear(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.YEAR);
    }

    public static Integer getYearCurrent() {
        return getYear(new Date());
    }

    public static Integer getMoonOfYearCurrent() {
        return getMoonOfYear(new Date());
    }


    /**
     * 2020年2月比2020年1月大1
     */
    public static Integer moonBiggerThan(Date d1, Date d2) {
        Calendar c = Calendar.getInstance();
        c.setTime(d1);
        int y1 = c.get(Calendar.YEAR);
        int m1 = c.get(Calendar.MONTH);
        c.setTime(d2);
        int y2 = c.get(Calendar.YEAR);
        int m2 = c.get(Calendar.MONTH);
        return 12 * (y1 - y2) + (m1 - m2);
    }

    public static Date createDate(Integer year, Integer moon, Integer day) {
        try {
            return dayDateFormat.parse(year + "-" + moon + "-" + day + " 00:00:00");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private final static long timeMillisOfOneDay = 1000 * 60 * 60 * 24;

    public static long dayBiggerThan(Date d1, Date d2) {
        return d1.getTime() / timeMillisOfOneDay - d2.getTime() / timeMillisOfOneDay;
    }


    private static DateFormat dayDateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");

    private static Date nextDay() {
        try {
            Date date = dayDateFormat.parse(dayDateFormat.format(new Date()));
            return DateCalculator.addDay(date, 1);
        } catch (Exception ignore) {
            return null;
        }
    }

}
